package com.sendables;

import java.nio.ByteBuffer;

import util.Util;

public class Text extends Sendable {
	public String	str;

	public Text(String str)
	{
		this.str = str;
	}

	public int getAlloc()
	{
		return str.getBytes().length + 4;
	}

	public static int calculateAlloc(String str)
	{
		return str.getBytes().length + 4;
	}

	public boolean equals(Object o)
	{
		if (o != null && o.getClass().equals(this.getClass()) && o instanceof Text)
		{
			Text t = (Text) o;
			if (str.equals(t.str))
			{
				return true;
			}
		}
		return false;
	}

	public String getContent()
	{
		return str;
	}

	public String toString()
	{
		return getClass().getCanonicalName() + "[str=" + str + "]";
	}

	public String setContent(String str)
	{
		String old = this.str;
		this.str = str;
		return old;
	}

	public byte[] getByteRepresentation()
	{
		byte[] bb = str.getBytes();
		byte[] b = new byte[4 + bb.length]; // type + 4*byte (length ) + the
		// bytes
		int offset = 0;
		Util.fill(b, ByteBuffer.allocate(4).putInt(bb.length).array(), offset);
		offset += 4;
		Util.fill(b, bb, offset);
		return b;
	}

	public void writeByteRepresentation(byte[] b, int[] offset)
	{
		byte[] strB = str.getBytes();
		byte[] sizeB = ByteBuffer.allocate(4).putInt(strB.length).array();
		Util.fill(b, sizeB, offset);
		offset[0] += 4;
		Util.fill(b, strB, offset);
		offset[0] += strB.length;
	}

	public static Text parse(byte[] b, int[] offset)
	{
		int size = ByteBuffer.wrap(b, offset[0], b.length - offset[0]).getInt();
		offset[0] += 4;
		Text t = new Text(new String(b, offset[0], size));
		offset[0] += size;
		return t;
	}

	public static void main(String[] args)
	{
		Text t = new Text("Hej, jag heter David");
		byte[] b = new byte[99];
		t.writeByteRepresentation(b, new int[] { 0 });
		Util.print(b, " ");
		Text tt = Text.parse(b, new int[] { 0 });
		System.out.println(t.getContent());
		System.out.println(tt.getContent());
	}

}
